<script setup name="spotCheckWorkorder">
import {
  GetListAPI,
  AddDataAPI,
  EditDataAPI,
  GetDeiltsAPI,
  DelDataAPI,
  DispatchAPI,
  ExecuteAPI,
  AuditAPI,
  RevocationAPI,
  DocumentAuditAPI
} from '@/api/device/inspection/workorder.js'

import AddFrom from './addForm.vue'
// import useUserStore from '@/store/modules/user'

// vue3方法实例
const { proxy } = getCurrentInstance()

const { inspection_work_order_generation_mode, device_type, patrol_work_order_status } = proxy.useDict(
  'inspection_work_order_generation_mode',
  'patrol_work_order_status',
  'device_type'
)
// const userStore = useUserStore()
// 新增 || 修改 || 查看实例
const addFromRef = ref(null)

// 储存数据
const ruleForm = ref({})

// 按钮枚举
const btnList = ref([])

// 各种状态及小数据
const state = reactive({
  row: [], // 选中数据
  ids: '', // 选中id
  delDisabled: false, // 多选
  examineDisabled: false, // 单选
  btnloading: false, //保存加载状态
  total: 0, // 列表总数量
  isShow: false, // 新增弹窗状态
  auditShow: false, // 新增弹窗状态
  title: '新增', // 标题
  loading: false // 表格加载状态
})

// 列表数据
const tabelData = ref([])

// 列表枚举
const column = ref([
  { label: '巡检单号', prop: 'patrolNumber', width: '120' },
  { label: '状态', prop: 'status' },
  { label: '生成方式', prop: 'generationModeDict' },
  { label: '所属计划', prop: 'planName' },
  { label: '设备编号', prop: 'deviceCode' },
  { label: '设备名称', prop: 'deviceName', width: '120' },
  { label: '设备类型', prop: 'deviceTypeDict' },
  { label: '设备型号', prop: 'deviceUnitType' },
  { label: '设备位置', prop: 'lineName', width: '120' },
  { label: '巡检开始时间', prop: 'patrolStartTime', width: '120' },
  { label: '巡检结束时间', prop: 'patrolEndTime', width: '120' },
  { label: '实际巡检工时', prop: 'maintenanceWorkHour', width: '120' },
  { label: '班组', prop: 'groupName' },
  { label: '巡检人数', prop: 'patrolNumberPeople' },
  { label: '操作', prop: 'x' }
])

// 查询条件
const SelectList = ref([
  { label: '巡检单号', model: 'patrolNumber', type: '输入框' },
  { label: '设备编号', model: 'deviceCode', type: '输入框' },
  { label: '设备名称', model: 'deviceName', type: '输入框' },
  {
    label: '状态',
    model: 'status',
    type: '下拉单选',
    opt: patrol_work_order_status
  },
  { label: '班组', model: 'groupCode', type: '输入框' },
  { label: '设备位置', model: 'installationLocation', type: '输入框' }
])

// 查询条件 分页
const query = reactive({
  pageNum: 1,
  pageSize: 10
})

// 条件查询
const selectSubmit = obj => {
  Object.keys(obj).forEach(itemKey => (query[itemKey] = obj[itemKey]))
  getList()
}

// 初始化按钮
const initBtn = () => {
  btnList.value = [
    {
      label: '新增',
      type: 'add',
      hasPermi: 'device:inspection:project:add'
    }
  ]
}
initBtn()

// 勾选列表数据时
const handleSelectionChange = ({ ids, row }) => {
  state.ids = ids
  state.rows = row
  state.multipleDis = !row.length
  state.singleDis = row.length != 1
  initBtn()
}
handleSelectionChange({ ids: [], row: [] })

// 新增弹窗
const addDic = () => {
  state.title = '新增'
  state.isShow = true
}

// 修改弹窗
const editDic = async id => {
  state.title = '修改'
  proxy.loading('请求中，请稍后')
  try {
    const { data: res } = await GetDeiltsAPI(id)
    ruleForm.value = res
    state.isShow = true
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 查看弹窗
const seeDic = async id => {
  proxy.loading('请求中，请稍后')
  try {
    const { data: res } = await GetDeiltsAPI(id)
    ruleForm.value = res
    state.title = '查看'
    state.auditShow = true
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 派工
const dispatch = async id => {
  proxy.loading('请求中，请稍后')
  try {
    const { data: res } = await GetDeiltsAPI(id)
    ruleForm.value = res
    state.isShow = true
    state.title = '派工'
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 执行巡检
const maintenance = async id => {
  proxy.loading('请求中，请稍后')
  try {
    const { data: res } = await GetDeiltsAPI(id)
    ruleForm.value = res
    // 判断 只有是派工成员才可执行
    // const suerIdFind = res.groupMemberList.find(item => item.id == userStore.userId || item.id == res.groupMonitor)
    // if (!suerIdFind) return proxy.warningMsg('只能是派工成员执行维修！')
    state.isShow = true
    state.title = '执行巡检'
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

//通过title判断执行事件
const isSub = () => {
  if (state.title == '新增') addSub()
  if (state.title == '修改') editSub()
  if (state.title == '派工') dispatchSub()
  if (state.title == '执行巡检') maintenanceSub()
}

// 新增提交后台
const addSub = async () => {
  const result = await addFromRef.value.submit()
  if (!result) return
  if (result.maintenanceProjects.length < 1) return proxy.warningMsg('至少选择一条巡检项目')
  result.patrolItemIdStr = result.maintenanceProjects.map(item => item.id).join(',')
  state.btnloading = true
  try {
    await AddDataAPI({
      patrolItemIdStr: result.patrolItemIdStr,
      deviceId: result.deviceId
    })
    getList()
    close()
    proxy.successMsg('新增成功！')
  } catch (err) {
    console.error(err)
  } finally {
    state.btnloading = false
  }
}

// 修改提交后台
const editSub = async () => {
  const result = await addFromRef.value.submit()
  if (!result) return
  // if (result.maintenanceProjects.length < 1) return proxy.warningMsg('至少选择一条巡检项目')
  // result.maintenanceProjectIdStr = result.maintenanceProjects.map(item => item.id).join(',')
  // 字符串人员
  result.patrolItemIdStr = result.maintenanceNumberPeoplea.join(',')
  // 人数
  result.maintenanceNumberPeople = result.maintenanceNumberPeoplea.length
  result.patrolWorkOrderProjectVoList = result.patrolItemList

  state.btnloading = true
  try {
    await EditDataAPI(result)
    getList()
    close()
    proxy.successMsg('修改成功！')
  } catch (err) {
    console.error(err)
  } finally {
    state.btnloading = false
  }
}

// 派工提交
const dispatchSub = async () => {
  const result = await addFromRef.value.submit()
  if (!result) return
  // 字符串人员
  result.patrolPeopleIdStr = result.maintenanceNumberPeoplea.join(',')
  // 人数
  result.maintenanceNumberPeople = result.maintenanceNumberPeoplea.length
  result.maintenanceWorkOrderProjectList = result.maintenanceProjectList

  state.btnloading = true
  try {
    await DispatchAPI(result)
    getList()
    close()
    proxy.successMsg('派工成功！')
  } catch (err) {
    console.error(err)
  } finally {
    state.btnloading = false
  }
}

// 执行巡检
const maintenanceSub = async () => {
  const result = await addFromRef.value.submit()
  if (!result) return
  result.patrolWorkOrderProjectVoList = result.patrolItemList
  state.btnloading = true
  try {
    await ExecuteAPI(result)
    getList()
    close()
    proxy.successMsg('执行巡检成功！')
  } catch (err) {
    console.error(err)
  } finally {
    state.btnloading = false
  }
}

// 审核提交
const eamineSub = async val => {
  const result = await addFromRef.value.submit()
  if (!result) return
  state.btnloading = true
  try {
    await DocumentAuditAPI({
      id: result.id,
      auditResult: val,
      auditOpinion: result.auditOpinion
    })
    getList()
    state.examineShow = false
    proxy.successMsg('审核成功！')
  } catch (err) {
    console.error(err)
  } finally {
    state.btnloading = false
  }
}

// 删除
const remove = async id => {
  const isif = await proxy.DelMessageBox()
  if (!isif) return
  proxy.loading('删除中，请稍后')
  try {
    await DelDataAPI(id)
    getList()
    close()
    proxy.successMsg('删除成功！')
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 提交审核
const review = async id => {
  const isif = await proxy.MessageBox('是否确认提交审核？')
  if (!isif) return
  proxy.loading('提交审核中，请稍后')
  try {
    await AuditAPI(id)
    getList()
    proxy.successMsg('提交成功！')
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 撤销审核
const revoke = async id => {
  const isif = await proxy.MessageBox('是否确认撤销审核？')
  if (!isif) return
  proxy.loading('撤销审核中，请稍后')
  try {
    await RevocationAPI(id)
    getList()
    proxy.successMsg('撤销成功！')
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 审核单据
const examine = async id => {
  proxy.loading('请求中，请稍后')
  try {
    const { data: res } = await GetDeiltsAPI(id)
    ruleForm.value = res
    state.examineShow = true
    state.title = '审核'
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 弹窗取消
const close = () => {
  state.isShow = false
  state.auditShow = false

  ruleForm.value = false
}

// 获取列表数据
const getList = async () => {
  state.loading = true
  try {
    const res = await GetListAPI(query)
    state.total = res.total
    tabelData.value = res.rows
  } catch (err) {
    console.error(err)
  } finally {
    state.loading = false
  }
}
getList()
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <p-table
        :loading="state.loading"
        keyId="id"
        :column="column"
        :data="tabelData"
        @change="handleSelectionChange"
        :total="state.total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      >
        <template #buttons>
          <!-- 按钮组件 -->
          <p-button :list="btnList" @add="addDic" @remove="batchRemove" />
        </template>
        <template #columnCell="{ column, record }">
          <p-dictTag v-if="column.prop == 'status'" :options="patrol_work_order_status" :value="record.status" />
          <p-operate
            v-if="column.prop == 'x'"
            :list="[
              {
                icon: 'Edit',
                emit: 'edit',
                text: '修改',
                type: 'primary',
                disabled: record.status != 5,
                hasPermi: 'device:spotCheck:workorder:edit'
              },
              {
                icon: 'Delete',
                emit: 'remove',
                text: '删除',
                type: 'danger',
                disabled: record.status != 1,
                hasPermi: 'device:spotCheck:workorder:remove'
              },
              {
                icon: 'Search',
                emit: 'look',
                text: '查看',
                type: 'primary',
                disabled: record.status == 1,
                hasPermi: 'device:spotCheck:workorder:query'
              },
              {
                icon: '',
                emit: 'dispatch',
                text: '派工',
                type: 'primary',
                disabled: record.status != 1,
                hasPermi: 'device:spotCheck:workorder:dispatch'
              },
              {
                icon: '',
                emit: 'maintenance',
                text: '执行巡检',
                type: 'primary',
                disabled: record.status != 2,
                hasPermi: 'device:spotCheck:workorder:maintenance'
              },
              {
                icon: '',
                emit: 'review',
                text: '提交审核',
                type: 'primary',
                disabled: record.status != 3,
                hasPermi: 'device:spotCheck:workorder:review'
              },
              {
                icon: '',
                emit: 'revoke',
                text: '撤销审核',
                type: 'primary',
                disabled: record.status != 4,
                hasPermi: 'device:spotCheck:workorder:revoke'
              },
              {
                icon: '',
                emit: 'examine',
                text: '审核单据',
                type: 'primary',
                disabled: record.status != 4 && record.status != 6,
                hasPermi: 'device:spotCheck:workorder:examine'
              }
            ]"
            @edit="editDic(record.id)"
            @remove="remove(record.id)"
            @look="seeDic(record.id)"
            @dispatch="dispatch(record.id)"
            @maintenance="maintenance(record.id)"
            @review="review(record.id)"
            @revoke="revoke(record.id)"
            @examine="examine(record.id)"
          />
        </template>
      </p-table>
    </el-card>
    <!-- 新增 || 修改 || 查看弹框 -->
    <p-dialog v-model="state.isShow" @ok="isSub" :title="state.title" @close="close" width="60%">
      <template #body>
        <AddFrom ref="addFromRef" :title="state.title" :disabled="state.title != '新增'" :data="ruleForm" />
      </template>
    </p-dialog>

    <!-- 审核弹窗 -->
    <p-dialog isEamine v-model="state.examineShow" width="60%" :title="state.title" @ok="eamineSub" @close="close">
      <p-auditHistory
        title="基本信息"
        :auditDoc="ruleForm.maintenanceNumber"
        perms="device:inspection:workorder:examine"
      >
        <AddFrom ref="addFromRef" :title="state.title" :disabled="state.title != '新增'" :data="ruleForm" />
      </p-auditHistory>
    </p-dialog>

    <!-- 审核查看 -->
    <p-dialog v-model="state.auditShow" :title="state.title" @close="close" width="60%">
      <template #body>
        <auditHistory title="工单信息" :auditDoc="ruleForm.patrolNumber" perms="device:inspection:workorder:examine">
          <template #body>
            <AddFrom ref="addFromRef" title="查看" :disabled="true" :data="ruleForm" />
          </template>
        </auditHistory>
      </template>
    </p-dialog>
  </div>
</template>

<style lang="scss" scoped>
.box-card {
  margin-top: 20px;
}
</style>
